﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Data;
namespace Tools.Other
{
    public class JsonHelper
    {
        private static void AddNewJson(StringBuilder Json, List<string> result, DataTable dt)
        {
            Json.Append("[");
            Json.Append("{");
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                Json.Append("\"");
                Json.Append(dt.Columns[i].ColumnName);
                Json.Append("\":");
                if (result[i].Contains(","))
                {
                    Json.Append("[");
                    Json.Append(result[i]);
                    if (i == dt.Columns.Count - 1)
                    {
                        Json.Append("]");
                    }
                    else
                    {
                        Json.Append("],");
                    }
                }
                else
                {
                    Json.Append(result[i]);
                    if (i != dt.Columns.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("}");
            Json.Append("]");
        }

     


        public static string DataTableToJson(DataTable dt)//不使用DLL
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{\"");
            jsonBuilder.Append(dt.TableName.ToString());
            jsonBuilder.Append("\":[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        public static string DataTableToJson(DataTable dt, string cols)//不使用DLL
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{\"");
            jsonBuilder.Append(dt.TableName.ToString());
            jsonBuilder.Append("\":[");
            string[] col = cols.Split(',');
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < col.Length; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(col[j]);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][col[j]].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        //[{"name":"nlstock","payment":"CS15","paymenttext":"OA 15 days","shipment":"EXW","shipmenttext":"NL Warehouse"}]
        public static DataTable JsonToDataTable(string strJson)//不使用DLL,   请使用JsonChangeToDataTable
        {
            //取出表名
            Regex rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));
            //获取数据
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split(',');
                //创建表
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        DataColumn dc = new DataColumn();
                        string[] strCell = str.Split(':');
                        dc.ColumnName = strCell[0].ToString().Replace("\"", "");
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }
                //增加内容
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split(':')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }
            return tb;
        }

        /// <summary>
        /// JsonToDataTable更新版,因jsonToDataTable如果内容中有逗号，则产生的数据有问题
        /// </summary>
        /// <param name="json"></param>
        public static DataTable JsonChangeToDataTable(string json)
        {
            System.Web.Script.Serialization.JavaScriptSerializer jss =
                new System.Web.Script.Serialization.JavaScriptSerializer();
            object[] obj = (object[])jss.DeserializeObject(json);
            Dictionary<string, object> dic;
            DataTable dt = new DataTable();
            for (int i = 0; i < obj.Length; i++)
            {
                dic = (Dictionary<string, object>)obj[i];
                if (i == 0)
                {
                    foreach (KeyValuePair<string, object> k in dic)
                    {
                        string key = k.Key;
                        dt.Columns.Add(key);
                    }
                }
                DataRow dr = dt.NewRow();
                foreach (KeyValuePair<string, object> k in dic)
                {
                    string key = k.Key;
                    object value = k.Value;

                    dr[key] = value;
                }
                dt.Rows.Add(dr);

            }

            return dt;
            //foreach (object _obj in obj)
            //{

            //}

        }

        public static bool Filter(ref string sInput)
        {
            if (sInput == null || sInput.Trim() == string.Empty)
                return false;
            string sInput1 = sInput.ToLower();
            //  string output = sInput;
            string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
            if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
            {
                //throw new Exception("字符串中含有非法字符!");
                return false;
            }
            else
            {
                sInput = sInput.Replace("'", "''");
            }
            return true;
        }

        public static string DataTableToJsonWithOutTableName(DataTable dt, bool isMap = false)
        {

            StringBuilder drs = new StringBuilder();
            DataColumnCollection dcc = dt.Columns;
            drs.Append("[");
            for (int index = 0; index < dt.Rows.Count; index++)
            {
                DataRow dr = dt.Rows[index];
                if (drs.Length > 2)
                {
                    drs.Append(",");
                }
                drs.Append("{");
                drs.Append("\"" + dcc[0].ColumnName.FirstToUpper(isMap) + "\"" + ":" + ToJson(dr[0].ToString()));    //第一个
                for (int i = 1; i < dcc.Count; i++)
                {
                    drs.Append(",\"" + dcc[i].ColumnName.FirstToUpper(isMap) + "\"" + ":" + ToJson(dr[i].ToString()));
                }
                drs.Append("}");

            }
            drs.Append("]");
            return drs.ToString();
        }

        public static string DataTableToJsonWithOutTableName(DataTable dt, string column, bool isMap = false)
        {

            StringBuilder drs = new StringBuilder();
            DataColumnCollection dcc = dt.Columns;
            drs.Append("[");
            string[] cols = column.Split(',');
            for (int index = 0; index < dt.Rows.Count; index++)
            {
                DataRow dr = dt.Rows[index];
                if (drs.Length > 2)
                {
                    drs.Append(",");
                }
                drs.Append("{");
                //drs.Append("\"" + dcc[0].ColumnName.FirstToUpper(isMap) + "\"" + ":" + ToJson(dr[0].ToString()));    //第一个
                for (int i = 0; i < cols.Length; i++)
                {
                    string colName = cols[i];
                    if (i != 0)
                    {
                        drs.Append(",");
                    }
                    drs.Append("\"" + colName.FirstToUpper(isMap) + "\"" + ":" + ToJson(dr[colName].ToString()));
                }
                drs.Append("}");

            }
            drs.Append("]");
            return drs.ToString();
        }

        public static string ToJson(object Msg)
        {

            var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            string jsonString = jss.Serialize(Msg);
            return jsonString;

        }

        public static T JsonToObject<T>(string json)
        {
            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            T someObject = jss.Deserialize<T>(json);
            return someObject;
        }
    }
}
